﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace DAO
{
    public class Data
    {
        SqlConnection con;
        private string cs;
        public static string error;
        public Data()
        {
            //cs = "Data Source=GATEWAY-PC\\SQLEXPRESS;Initial Catalog=ROBATA;Integrated Security=True";
            cs = ConfigurationManager.ConnectionStrings["KetNoi"].ConnectionString;
            con = new SqlConnection(cs);
        }
        public bool mo()
        {
            try
            {
                if (con == null)
                {
                    con = new SqlConnection(cs);
                }
                if (con.State == ConnectionState.Open)
                {
                    con.Close();
                }
                con.Open();
                return true;
            }
            catch (SqlException ex)
            {
                error = ex.ToString();
                return false;
            }
        }
        public bool ExecuteNonQuery(string sql)
        {
            try
            {
                if (mo())
                {
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                    error = "";
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (SqlException ex)
            {
                error = ex.ToString();
                return false;
            }
            finally
            {
                con.Close();
            }
        }
        public DataTable ExecuteQuery(string sql)
        {
            DataTable dt = new DataTable();
            try
            {
                if (mo())
                {
                    SqlCommand cmd = con.CreateCommand();
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandText = sql;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    error = "";
                    return dt;
                }
                else
                {
                    return dt;
                }
            }
            catch (SqlException ex)
            {
                error = ex.ToString();

                return dt;
            }
            finally
            {
                con.Close();
            }
        }
    }
}
